package com.yq.tanhua.ui.publish

import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.lifecycleScope
import coil.compose.rememberAsyncImagePainter
import com.blankj.utilcode.util.ToastUtils
import com.fmt.mvi.learn.gobal.log
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.yq.tanhua.net.TanHuaApiService
import com.yq.tanhua.net.dto.MovementDto
import com.yq.tanhua.utils.ImageFileCompressEngine
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import top.zibin.luban.OnNewCompressListener
import utils.FileUtils
import java.io.File
import java.net.URI

class PublishActivity : AppCompatActivity() {

    var inputContent = mutableStateOf("")
    val pictureList = mutableStateListOf<String>().apply {
        add("add")
    }

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Spacer(Modifier.height(20.dp))
                    TextField(
                        value = inputContent.value,
                        onValueChange = { result ->
                            inputContent.value = result
                        },
                        label = { Text(text = "表达点什么吧") },
                        modifier = Modifier
                            .fillMaxWidth(1f)
                            .defaultMinSize(minHeight = 140.dp)
                            .padding(horizontal = 20.dp)
                            .shadow(1.dp),
                        colors = TextFieldDefaults.textFieldColors(
                            containerColor = Color.Transparent,
                            focusedIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent
                        )
                    )
                    Spacer(Modifier.height(40.dp))
                    LazyVerticalGrid(
                        columns = GridCells.Fixed(3),
                        modifier = Modifier.padding(horizontal = 15.dp),
                        content = {

                            itemsIndexed(pictureList) { index, item ->
                                if ("add".equals(item)) {

                                    Text(
                                        text = "+",
                                        textAlign = TextAlign.Center,
                                        modifier = Modifier
                                            .padding(5.dp)
                                            .width(100.dp)
                                            .height(100.dp)
                                            .border(1.dp, Color.Gray)
                                            .clickable {
                                                selectPicture()
                                            },
                                        fontSize = 80.sp
                                    )
                                } else {
                                    Image(
                                        painter = rememberAsyncImagePainter(model = item),
                                        contentDescription = null,
                                        modifier = Modifier
                                            .padding(5.dp)
                                            .size(100.dp, 100.dp),
                                        contentScale = ContentScale.Crop
                                    )
                                }
                            }
                        })
                    Button(
                        modifier = Modifier.padding(top = 22.dp),
                        onClick = {
                            publish()
                        }) {
                        Text(text = "发布")
                    }
                }
            }

        }
    }

    fun selectPicture() {

        PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(ImageFileCompressEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    result?.let {
                        it[0]?.let {
                            it.compressPath.log()
                            val file = File(it.compressPath)
                            file.length().log()
                            pictureList.add(0, it.compressPath)
                        }
                    }
                }

                override fun onCancel() {}
            })
    }


    fun publish() {
        if (inputContent.value.isEmpty()) {
            ToastUtils.showShort("必须表达")
            return
        }
        lifecycleScope.launch {
            val builder = MultipartBody.Builder()
            for (pic in pictureList) {
                if ("add" == pic) {
                    continue
                }
                val file = File(pic)
                val body = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
                builder
                    .addFormDataPart("imageContent", "head.jpg", body)
            }
            var build: MultipartBody? = null
            if (pictureList.size > 1) {
                build = builder.setType(MultipartBody.FORM).build()
            }

            kotlin.runCatching {

                val movementDto = MovementDto()
                movementDto.textContent = inputContent.value
                val textContent =
                    movementDto.textContent.toRequestBody("text/plain".toMediaTypeOrNull())
                val locationName =
                    "河南".toRequestBody("text/plain".toMediaTypeOrNull())
                TanHuaApiService.publishMovment(textContent, locationName, build?.parts)

            }.onSuccess {
                if (it.code != 0) {
                    throw Exception("上传失败啦${it.code}")
                }
                "上传成功".log()
                ToastUtils.showLong("上传成功")
                finish()
            }.onFailure {
                it.printStackTrace()
                ToastUtils.showLong("上传失败")
                "上传失败".log()
            }
        }

    }
}